const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    defAvatar: '/images/defAvatar.png',
    companyInfo: undefined,
    newLists: undefined,
    solutionLists: undefined,
    showMpjbutton: false,
    openShare: false,
    cardUserInfo: {},
    kActionType: {},
    content: '...',
    qrcode: undefined,
    isExpandAll: false,
    isExpandUserInfo: false,
    phoneNumber: undefined,
    bannerList: undefined,
    backUrl: undefined,
    color: "rgb(195,194,203)",
    selectedColor: "rgb(0, 131, 255)",
    tabBarList: [{
        id: 1,
        pagePath: "/pages/card/main",
        iconPath: "/images/v1/share.png",
        activePath: "/images/v1/share-active.png",
        text: "分享名片"
      },
      {
        id: 2,
        pagePath: "/pages/complain/main",
        iconPath: "/images/v1/complain.png",
        activePath: "/images/v1/complain-active.png",
        text: "投诉建议"
      },
      {
        id: 3,
        pagePath: "/pages/card/main",
        iconPath: "/images/v1/service2.svg",
        activePath: "/images/v1/share-active.png",
        text: '智能助手'
      },
      {
        id: 4,
        pagePath: "/pages/policy/main",
        iconPath: "/images/v1/policy.png",
        activePath: "/images/v1/policy-active.png",
        text: "政策宣传"
      },
      {
        id: 5,
        pagePath: "/pages/notice/main",
        iconPath: "/images/v1/notice.png",
        activePath: "/images/v1/notice-active.png",
        text: "通知公告"
      },
    ],
    miniAppRole: undefined
  },

  /** * 生命周期函数--监听页面加载 */
  onLoad: function (e) {
    // console.log('main-onLoad');
    wx.login({
      success: (res) => {
        wx.setStorageSync('code', res.code)
      }
    })
    if (e.url && e.companyId && e.userId) {
      let backUrl = e.url + '?companyId=' + e.companyId + '&userId=' + e.userId
      this.setData({
        backUrl
      })
      // console.log(backUrl);
    } else {
      this.setData({
        backUrl: false
      })
    }

  },
  /** * 生命周期函数--监听页面初次渲染完成 */
  onReady: function () {

  },
  /** * 生命周期函数--监听页面显示 */
  async onShow() {
    WXAPI.initPage(this)

    // this.initData()
    wx.hideTabBar({
      animation: false,
    })
    // console.log('main--onShow')

    this.setData({
      phoneNumber: wx.getStorageSync('phoneNumber'),
      cardUserInfo: wx.getStorageSync('userInfo'),
      miniAppRole: wx.getStorageSync('miniAppRole')
    })
    if (wx.getStorageSync('miniAppRole') != 'Waiter') {
      this.getBanner()
    }
    if (this.data.cardUserInfo && wx.getStorageSync('miniAppRole') != 'Waiter') {
      this.getCompanyDif(this.data.cardUserInfo.company.id)
      this.setData({
        cardUserInfo: false
      })
    }
    if (wx.getStorageSync('miniAppRole') == 'Waiter') {
      this.getUserInfo()
    }
  },

  /** * 生命周期函数--监听页面隐藏 */
  onHide: function () {

  },
  /** * 生命周期函数--监听页面卸载 */
  onUnload: function () {

  },

  /** * 页面相关事件处理函数--监听用户下拉动作 */
  onPullDownRefresh: function () {

  },

  // 页面上拉触底事件的处理函数 *
  onReachBottom: function () {

  },

  // 用户点击右上角分享
  onShareAppMessage: function () {
    return {
      title: this.data.cardUserInfo.user.userName + ' ' + this.data.cardUserInfo.company.name + '，请惠存我的名片。',
      path: '/pages/other-card/main?userId=' + this.data.cardUserInfo.user.userId + '&companyId=' + this.data.cardUserInfo.company.id,
    }
  },
  //获取顶部广告轮播
  getBanner() {
    let data = {}
    if (wx.getStorageSync('companyId')) {
      data.companyId = wx.getStorageSync('companyId')
    }
    if (wx.getStorageSync('myCompanyId')) {
      data.companyId = wx.getStorageSync('myCompanyId')
    }
    WXAPI.getBanner(data).then(res => {
      // console.log(res);
      if (res.code == 200) {
        this.setData({
          bannerList: res.data
        })
      } else {
        this.setData({
          bannerList: []
        })
      }
    }).catch(err => {
      console.log(err);
      this.setData({
        bannerList: []
      })
    })
  },
  //首页按钮跳转智能客服链接
  toEchoLink() {
    WXAPI.getCardCustomerOwnerStatus(wx.getStorageSync('phoneNumber')).then(res => {
        let companyId = 0
        if (res.code == 200) { //有白名单信息
          wx.setStorageSync('appToken', res.data.appToken)
          wx.setStorageSync('companyId', res.data.companyId)
          companyId = res.data.companyId
        }
        WXAPI.getCompanyById(companyId).then(res => {
          console.log(res);
          if (res.code == 200) {
            let url = encodeURIComponent(res.data.echoLink)
            wx.navigateTo({
              url: '/pages/out/main?echoLink=' + url
            })
          } else {
            wx.showToast({
              title: '加载失败',
            })
          }
        }).catch(err => {
          wx.showToast({
            title: '加载失败',
          })
        })
      })
      .catch(err => {
        WXAPI.getCompanyById(0).then(res => {
          console.log(res);
          if (res.code == 200) {
            let url = encodeURIComponent(res.data.echoLink)
            wx.navigateTo({
              url: '/pages/out/main?echoLink=' + url
            })
          } else {
            wx.showToast({
              title: '加载失败',
            })
          }
        }).catch(err => {
          wx.showToast({
            title: '加载失败',
          })
        })
      })


  },
  //跳转备用名片
  goStandby() {
    wx.navigateTo({
      url: '/pages/standby/main?companyId=' + this.data.cardUserInfo.company.id + '&userId=' + this.data.cardUserInfo.user.userId,
    })
  },
  //获取手机号登陆
  getPhoneNumber(e) {
    console.log('getPhoneNumber', e);
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      AUTH.register(this, e.detail, wx.getStorageSync('backUrl') || false);
    } else {
      wx.showModal({
        title: '授权失败',
        content: '无法获取手机号登录',
        showCancel: false
      })
    }
  },
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        // console.log(res);
      }
    })
  },
  //获取用户信息
  getUserInfo() {
    WXAPI.getUserInfo().then((res) => {
      if (res.code === 200) {
        this.getCompanyDif(res.data.company.id)
        this.setData({
          cardUserInfo: res.data,
        })
        wx.setStorageSync('userId', res.data.user.userId)
        wx.setStorageSync('userInfo', res.data)
        wx.setStorageSync('myCompanyId', res.data.company.id)
        this.getBanner()
      } else {
        wx.clearStorageSync()
        wx.login({
          success: (res) => {
            wx.setStorageSync('code', res.code)
          },
        })
        wx.showToast({
          title: '请重新登陆',
          icon: 'error'
        })
        this.onShow()
      }
    }).catch(err => {
      fail: (res) => {
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        })
      }
    })
  },
  //获取公司信息
  getCompanyDif(id) {
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 3,
      type: 1
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          newLists: res.data.list
        })
      } else {
        this.setData({
          newLists: []
        })
      }
    }).catch(err => {
      this.setData({
        newLists: []
      })
    })
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 3,
      type: 2
    }).then(res => {

      if (res.code == 200) {
        this.setData({
          solutionLists: res.data.list
        })
      } else {
        this.setData({
          solutionLists: []
        })
      }
    }).catch(err => {
      this.setData({
        solutionLists: []
      })
    })
    WXAPI.getCompanyDif({
      cardCompanyId: id,
      pageNum: 1,
      pageSize: 1,
      type: 3
    }).then(res => {
      if (res.code == 200) {
        this.setData({
          companyInfo: res.data.list[0] || false
        })
      } else {
        this.setData({
          companyInfo: []
        })
      }
    }).catch(err => {
      this.setData({
        companyInfo: []
      })
    })
  },
  //复制信息
  copyData(e) {
    const v = e.currentTarget.dataset.v
    wx.setClipboardData({
      data: v,
      success: (res) => {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        })
      }
    })
  },
  //展开公司信息
  expandAll() {
    this.setData({
      isExpandAll: !this.data.isExpandAll
    })
  },
  //展开个人信息
  expandAllUserInfo() {
    this.setData({
      isExpandUserInfo: !this.data.isExpandUserInfo
    })
  },
  //查看图片
  previewImage: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      // current: current, // 当前显示图片的http链接  
      urls: [current] // 需要预览的图片http链接列表  
    })
  },
  //跳转智能客服
  goOutUrl: function (e) {
    let url = encodeURIComponent(this.data.cardUserInfo.company.echoLink)
    wx.navigateTo({
      url: '/pages/out/main?echoLink=' + url
    })
  },
  //查看政策通知详情
  goDetail(e) {
    wx.navigateTo({
      url: '/pages/news-detail/main?news=' + JSON.stringify(e.currentTarget.dataset.news)
    })
  },
  goAd(e) {
    let url = encodeURIComponent(e.currentTarget.dataset.url)
    if (url && url.length) {
      wx.navigateTo({
        url: '/pages/ad/main?adUrl=' + url
      })
    }
  },
  switchTab(e) {
    const data = e.currentTarget.dataset
    const url = data.path + '?id=' + this.data.cardUserInfo.company.id
    this.setData({
      selected: data.index
    })
    if (data.index == 1) {

    } else if (data.index == 2) {
      this.setData({
        selected: data.index
      })
      let suggestionLink = encodeURIComponent(this.data.cardUserInfo.company.suggestionLink)
      wx.navigateTo({
        url: '/pages/complain/main?suggestionLink=' + suggestionLink
      })

    } else if (data.index == 3) {
      this.goOutUrl()
    } else if (data.index == 4 || data.index == 5) {
      this.setData({
        selected: data.index
      })
      console.log(url);
      wx.navigateTo({
        url: url
      })
    }
  },
  initData() {
    this.setData({
      companyInfo: false,
      newLists: false,
      solutionLists: false,
      showMpjbutton: false,
      openShare: false,
      cardUserInfo: false,
      content: '...',
      isExpandAll: false,
      isExpandUserInfo: false,
      phoneNumber: false,
      bannerList: false,
      backUrl: false,
      miniAppRole: false
    })
  }
})